package com.tpvlog.dfs.datanode.file;

import java.io.File;

import static com.tpvlog.dfs.datanode.config.DataNodeConfig.DATA_DIR;

/**
 * 负责文件存储管理的组件
 *
 * @author Ressmix
 */
public class StorageManager {

    /**
     * 获取DataNode的存储信息
     */
    public DataNodeInfo getStorageInfo() {
        DataNodeInfo dataNodeInfo = new DataNodeInfo();
        File rootDir = new File(DATA_DIR);
        File[] children = rootDir.listFiles();
        if (children != null || children.length > 0) {
            for (File child : children) {
                scanFiles(child, dataNodeInfo);
            }
        }
        return dataNodeInfo;
    }

    /*------------------------------------------------PRIVATE METHOD--------------------------------------------*/

    /**
     * 递归扫描文件信息
     *
     * @param rootDir
     */
    private void scanFiles(File rootDir, DataNodeInfo dataNodeInfo) {
        if (rootDir.isFile()) {
            String path = rootDir.getPath();
            path = path.substring(DATA_DIR.length());
            path = path.replace("\\", "/"); // /image/product/iphone.jpg
            dataNodeInfo.addFilename(path);
            dataNodeInfo.addStoredDataSize(rootDir.length());
            return;
        }
        File[] children = rootDir.listFiles();
        if (children == null || children.length == 0) {
            return;
        }
        for (File child : children) {
            scanFiles(child, dataNodeInfo);
        }
    }
}
